package chat.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

import chat.client.ui.ChatUI;

public class Client {
	private static volatile boolean exit = false;

	private static class SocketReaderThread implements Runnable {
		BufferedReader in = null;
		String fromUser = null;
		String toUser = null;
		ChatUI ui = null;
		SocketReaderThread(BufferedReader reader, String fromUser, String toUser,ChatUI ui) {
			this.in = reader;
			this.fromUser = fromUser;
			this.toUser = toUser;
			this.ui = ui;
		}

		@Override
		public void run() {
			String str = null;
			try {
				while ((str = in.readLine()) != null) {
					if (str.equals("bye")) {
						System.out.println("Exiting the Chat");
						exit = true;
					}
//					System.out.println();
//					System.out.println("From " + toUser + " : " + str);
//					System.out.println();
					ui.setReceiverData(str, toUser);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void startClient() {
		BufferedWriter out = null;
		BufferedReader in = null;
		Socket socket = null;
		Scanner keyboardReader = new Scanner(System.in);
		try {
			// Connect to server
			socket = new Socket("localhost", 8099);

			// get the output stream and input stream to read and write into the
			// server
			out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			// create the current user and to user to whom you need to chat.
			System.out.print("Enter UserName : ");
			String fromUser = keyboardReader.nextLine();
			out.write(fromUser);
			out.write("\n");
			out.flush();
			System.out.print("Enter To User : ");
			String toUser = keyboardReader.nextLine();
			out.write(toUser);
			out.write("\n");
			out.flush();
			// read from the socket and print it.
			
			ChatUI ui = new ChatUI(out,fromUser);
			ui.constructChatWindow();
			
			Thread response = new Thread(new SocketReaderThread(in, fromUser, toUser,ui));
			response.start();
			response.join();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (Exception e) {
				}
			}
		}
		keyboardReader.close();
	}

	public static void main(String[] args) {
		Client cli = new Client();
		cli.startClient();
	}
}